package com.mifengs.mall.ui.openself;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.mall.Constant;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.BaseFragment;
import com.mifengs.mall.entity.ContractPre;
import com.mifengs.mall.entity.ResponseBean;
import com.mifengs.mall.event.OpenSelfEvent;
import com.mifengs.mall.netWork.NetWork;
import com.mifengs.mall.ui.opencompany.AuditFragment;
import com.mifengs.mall.ui.write.HandWrittenActivity;
import com.mifengs.mall.util.ToIntentUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by lynn on 2018/3/19.
 */

public class HandWriteFragment extends BaseFragment {


    @BindView(R.id.relative_img_view)
    RelativeLayout relativeImgView;
    @BindView(R.id.handwrite_btn)
    Button handwriteBtn;
    @BindView(R.id.handwrite_img)
    ImageView handwriteImg;
    @BindView(R.id.text_view)
    TextView textView;
    @BindView(R.id.btn_audit)
    Button btnAudit;
    @BindView(R.id.ll_contract_pre)
    LinearLayout llContractPre;
    @BindView(R.id.ll_contract_down)
    LinearLayout llContractDown;
    private boolean isSub = false;
    private HashMap<String, Object> hashMap;

    public static HandWriteFragment newInstance(HashMap<String, Object> hashMap) {
        HandWriteFragment fragment = new HandWriteFragment();
        fragment.hashMap = hashMap;
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_handwrite, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @OnClick({R.id.relative_img_view, R.id.handwrite_btn, R.id.btn_audit,R.id.ll_contract_pre, R.id.ll_contract_down})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.relative_img_view:
                startActivityForResult(new Intent(getContext(), HandWrittenActivity.class), Constant.HANDWRITE_RESULT);
                break;
            case R.id.handwrite_btn:
                startActivityForResult(new Intent(getContext(), HandWrittenActivity.class), Constant.HANDWRITE_RESULT);
                break;
            case R.id.btn_audit:
                if (isSub) {
                    selfMaterialSub();
                }
                break;
            case R.id.ll_contract_pre:
                toPreContract(1);
                break;
            case R.id.ll_contract_down:
                toPreContract(2);
                break;
        }
    }

    private void toPreContract(int type){
        String hPreviewUrl = (String) hashMap.get("hPreviewUrl");
        String hServer = (String) hashMap.get("hServer");
        String hDownloadUrl = (String) hashMap.get("hDownloadUrl");

        String mContractDownUrl =hServer+ hDownloadUrl;
        String mContractPreUrl = Constant.BaseUrl_H5 + hPreviewUrl;
        try {
            if (type == 1) {
                ToIntentUtil.toCommonIntent(mContractPreUrl, getActivity());
            } else {
                Uri uri = Uri.parse(mContractDownUrl);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        }catch (Exception e){
            e.toString();
        }
    }

    public void selfMaterialSub() {
        showLoading();
        NetWork.getMaterialSubApi().saveStoreCertificate(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBean<ContractPre>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUitl.show(e.getMessage().toString(),Toast.LENGTH_SHORT);
                        hideLoading();
                    }

                    @Override
                    public void onNext(ResponseBean<ContractPre> contractPreResponseBean) {
                        hideLoading();
                        if ("OK".equals(contractPreResponseBean.getMessage())) {
                            PreferenceUtils.saveBooleanPreference(getContext(),MaterialSubFragment.IS_SAVE,false);
                            OpenSelfEvent event = new OpenSelfEvent(OpenSelfEvent.TOAUDITPAGE);
                            event.auditStatus = AuditFragment.AuditStatus.AuditIng;
                            EventBus.getDefault().post(event);
                        }else{
                            ToastUitl.show(contractPreResponseBean.getMessage(), Toast.LENGTH_SHORT);
                        }
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Constant.HANDWRITE_RESULT) {
            isSub = true;
            String path = data.getStringExtra("path");
            String url = data.getStringExtra("url");
            if (hashMap != null) {
                hashMap.remove("persistent");
                hashMap.put("persistent", 1);
                hashMap.put("signature", url);
            }
            handwriteBtn.setText("重新手写签名");
            relativeImgView.setVisibility(View.GONE);
            textView.setVisibility(View.GONE);
            btnAudit.setBackgroundResource(R.drawable.btn_audit_bg_blue);
            Glide.with(this).load(path).into(handwriteImg);

        }
    }
}
